import pymysql
from settings import mysql_server
# 打开数据库连接
try:
    db = pymysql.connect(**mysql_server)
    print('mysql连接成功！')
except Exception as e:
    raise e

cursor=db.cursor()#!创建数据游标

def ins_del_upd(sql:str)->(bool,dict):#!数据库添加、删除、修改
    try:
        rowcount=cursor.execute(sql)
        db.commit()
        print("{}操作成功：【{}】".format(sql.split()[0],sql))
        return True,{"rowcount":rowcount}
    except Exception as e:
        print("操作失败：{}".format({"error": e, "sql": sql}))
        db.rollback()
        return False,{"error": e, "sql": sql}

def select(sql:str)->(bool,dict):#!数据搜索
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        db.commit()
        return True,results
    except Exception as e:
        return False,{"error": e, "sql": sql}
